﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.ReceptionGoods
{
    public partial class AddRowWithInnerGoods :  Form
    {
        public AddRowWithInnerGoods()
        {
            InitializeComponent();
        }
        private Int32 _docId;
        public Int32 DocId
        {
            get
            {
                return _docId;
            }
            set
            {
                _docId = value;
                
                
            }
        }
        WaybillsImportList _par;
        public AddRowWithInnerGoods(Int32 docId,WaybillsImportList par)
        {
            _docId = docId;
            _par = par;
            InitializeComponent();
        }
        DataSets.waybillsData.CurrentNaklRow _row;
        public DataSets.waybillsData.CurrentNaklRow CurrentRow
        {
            get
            {
                return _row;
            }
            set
            {
                _row = value;
            }
        }
        private Util.ActionType _openAction = DIProject.Util.ActionType.NoAction;
                
        public Util.ActionType OpenAction

        {
            get { return _openAction; }
            set { _openAction = value; }
        }
	
        public AddRowWithInnerGoods(DataSets.waybillsData.CurrentNaklRow row, Util.ActionType actType)
        {
            CurrentRow = row;
            OpenAction = actType;
            InitializeComponent();
        }
        private static AddRowWithInnerGoods _cashe;

        public static AddRowWithInnerGoods Cache
        {
            get { return _cashe; }
            set { _cashe = value; }
        }

        private DataSets.Dictionary.vwGoodsDetailedDataTable _dt;

        public DataSets.Dictionary.vwGoodsDetailedDataTable Data
        {
            get 
            {
                if (_dt == null)
                {
                    DataSets.DictionaryTableAdapters.vwGoodsDetailedTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.vwGoodsDetailedTableAdapter();
                    _dt = adapter.GetData();
                }
                return _dt; 
            }
            

        }
        private DataSets.waybillsData.SetificatedOrgDataTable _sert;

        public DataSets.waybillsData.SetificatedOrgDataTable Sert
        {
            get 
            {
                if (_sert == null)
                {
                    DataSets.waybillsDataTableAdapters.SetificatedOrgTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.SetificatedOrgTableAdapter();
                    _sert = adapter.GetData();
                }
                return _sert; 
            }
            
        }

        public void ClearData()
        {
            _dt = null;
            _sert = null;
        }
        private void AddRowWithInnerGoods_Load(object sender, EventArgs e)
        {
            if (cbCertificateOrg.DataSource == null)
                cbCertificateOrg.DataSource = this.Sert;
            if (OpenAction == DIProject.Util.ActionType.Update)
            {
                InitUpdate();
            }
            
        }

        
        private void InitUpdate()
        {
            rbNoNDS.Checked = false;
            txbCount.Text = CurrentRow.Count.ToString();
            if(!CurrentRow.IsRetailMarkupNull())
                txbMarkUp.Text = CurrentRow.RetailMarkup.ToString();
            selecter1.SelectedValue = CurrentRow.GoodsId;            
            selecter1.SelectedText = CurrentRow.FullName + " " + CurrentRow.ManufacturerName;
            if (!CurrentRow.IsRetailPriceNull())
                txbRetailPrice.Text = CurrentRow.RetailPrice.ToString();
            if (!CurrentRow.IsNDSTaxNull())
                txbNDSTax.Text = CurrentRow.NDSTax.ToString();
            if (!CurrentRow.IsSupplierSumNOTAXNull())
                txbSummNoNDS.Text = CurrentRow.SupplierSumNOTAX.ToString();
            if (!CurrentRow.IsSupplierPriceNull())
                txbPriceSupplaerWithNDS.Text = CurrentRow.SupplierPrice.ToString();
            if (!CurrentRow.IsNDSValueNull())
                txbNDSSumm.Text = CurrentRow.NDSValue.ToString();
            if (!CurrentRow.IsImportMarkupNull())
                txbImportMarkUp.Text = CurrentRow.ImportMarkup.ToString();
            if (!CurrentRow.IsManufacturerPriceNull())
                txbManufacturerPrice.Text = CurrentRow.ManufacturerPrice.ToString();
            if (!CurrentRow.IsReadyBeforeNull())
            {
                dtpReadyBefore.Checked = true;
                dtpReadyBefore.Value = CurrentRow.ReadyBefore;
            }
            if (!CurrentRow.IsMadeDateNull())
            {
                dtpMadeDate.Checked = true;
                dtpMadeDate.Value = CurrentRow.MadeDate;
            }
            if (!CurrentRow.IsReestrPriceNull())
                txbReestrPrice.Text = CurrentRow.ReestrPrice.ToString();
            if (!CurrentRow.IsReestrDateNull())
            {
                dtpReestrDate.Checked = true;
                dtpReestrDate.Value = CurrentRow.ReestrDate;
            }
            if (!CurrentRow.IsGTDNumberNull())
                txbGTDNumber.Text = CurrentRow.GTDNumber;
            if (!CurrentRow.IsCertificateNumberNull())
                txbCertificateNumber.Text = CurrentRow.CertificateNumber;
            if (!CurrentRow.IsCertificateDateNull())
            {
                dtpCertificateDate.Checked = true;
                dtpCertificateDate.Value = CurrentRow.CertificateDate;
            }
            if (!CurrentRow.IsSupplierMarkupNull())
                txbSupplierMarkUp.Text = CurrentRow.SupplierMarkup.ToString();
            if (!CurrentRow.IsNoteNull())
                txbNote.Text = CurrentRow.Note;
            if (!CurrentRow.IsBatchNumberNull())
                txbSerija.Text = CurrentRow.BatchNumber;

        }

        private void button3_Click(object sender, EventArgs e)
        {
            ClearData();
        }

        private void cbGoods_SelectedIndexChanged(object sender, EventArgs e)
        {
          /*  DataSets.waybillsDataTableAdapters.ManufacturerAndCountryTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.ManufacturerAndCountryTableAdapter();
            DataSets.waybillsData.ManufacturerAndCountryDataTable tab = adapter.GetData((Int32));
            DataSets.waybillsData.ManufacturerAndCountryRow row = tab.Rows[0] as DataSets.waybillsData.ManufacturerAndCountryRow;
            lbCountry.Text = row.CountryName;
            lbManufacturer.Text = row.ManufacturerName;*/
        }

        private void AddRowWithInnerGoods_Shown(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
        private void UpdateRow()
        {
            object ReadyBefore = null;
            if (this.dtpReadyBefore.Checked)
                ReadyBefore = this.dtpReadyBefore.Value;
            object MadeDate = null;
            if (this.dtpMadeDate.Checked)
                MadeDate = this.dtpMadeDate.Value;
            object ReestrDate = null;
            if (this.dtpReestrDate.Checked)
                ReestrDate = this.dtpReestrDate.Value;
            object CertificateDate = null;
            if (this.dtpCertificateDate.Checked)
                CertificateDate = this.dtpCertificateDate.Value;
            byte NDSTax = 10;
            if (!string.IsNullOrEmpty(this.txbNDSTax.Text))
                NDSTax = Convert.ToByte(this.txbNDSTax.Text);
            DataSets.waybillsDataTableAdapters.SupplierInvoiceLinesUpdateTableAdapter adap = new DIProject.DataSets.waybillsDataTableAdapters.SupplierInvoiceLinesUpdateTableAdapter();
            try
            {
               // Int32 Count;
                adap.GetData((Int32)selecter1.SelectedValue, CurrentRow.BarCode,
                    Convert.ToInt32(this.txbCount.Text), 
                    Util.Convert.ToInt32(this.txbCount.Text), 
                    CurrentRow.SupplierGoodsId,
                    Util.Convert.ToDecimal(this.txbManufacturerPrice.Text),
                    Util.Convert.ToDecimal(this.txbPriceSupplaerWithNDS.Text),
                    Util.Convert.ToDecimal(txbSummNoNDS.Text),
                    Util.Convert.ToDouble(this.txbImportMarkUp.Text),
                    Util.Convert.ToDouble(this.txbSupplierMarkUp.Text),
                    this.txbSerija.Text, Util.Convert.ToDateTime(ReadyBefore),
                    Util.Convert.ToDateTime(MadeDate),
                    NDSTax, Util.Convert.ToDecimal(this.txbNDSSumm.Text),
                    Util.Convert.ToDecimal(this.txbReestrPrice.Text),
                    Util.Convert.ToDateTime(ReestrDate),
                    this.txbGTDNumber.Text, this.txbCertificateNumber.Text,
                    Util.Convert.ToDateTime(CertificateDate), (Int32)this.cbCertificateOrg.SelectedValue,
                    Util.Convert.ToDouble(this.txbMarkUp.Text), Util.Convert.ToDecimal(this.txbRetailPrice.Text),
                    this.txbNote.Text, DateTime.Now, FirstForm.Login, CurrentRow.Id, CurrentRow.MD);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message,"Ошибка");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.OpenAction == DIProject.Util.ActionType.Update)
            {
                UpdateRow();
                this.Close();
                return;
            }
            if (!this.ValidateChildren(ValidationConstraints.Enabled))
                return;
            object ReadyBefore = null;
            if (this.dtpReadyBefore.Checked)
                ReadyBefore = this.dtpReadyBefore.Value;
            object MadeDate = null;
            if (this.dtpMadeDate.Checked)
                MadeDate = this.dtpMadeDate.Value;
            object ReestrDate = null;
            if (this.dtpReestrDate.Checked)
                ReestrDate = this.dtpReestrDate.Value;
            object CertificateDate = null;
            if (this.dtpCertificateDate.Checked)
                CertificateDate = this.dtpCertificateDate.Value;
            byte NDSTax = 10;
            if (!string.IsNullOrEmpty(this.txbNDSTax.Text))
                NDSTax = Convert.ToByte(this.txbNDSTax.Text);
            Int32 gId = (Int32)this.selecter1.SelectedValue;
            Int32 sertId = 1;
            if (this.cbCertificateOrg.SelectedValue != null)
                sertId = (Int32)this.cbCertificateOrg.SelectedValue;
            try
            {
                DIProject.Data.Nkld.SupplierInvoiceLinesInsert(_docId, gId, null,
                    Convert.ToInt32(this.txbCount.Text), Util.Convert.ToInt32(this.txbCount.Text), 1,
                    Util.Convert.ToDecimal(this.txbManufacturerPrice.Text), Util.Convert.ToDecimal(this.txbPriceSupplaerWithNDS.Text),
                    Util.Convert.ToDecimal(txbSummNoNDS.Text),
                    Util.Convert.ToDouble(this.txbImportMarkUp.Text), Util.Convert.ToDouble(this.txbSupplierMarkUp.Text),
                    this.txbSerija.Text, Util.Convert.ToDateTime(ReadyBefore), Util.Convert.ToDateTime(MadeDate),
                    NDSTax, Util.Convert.ToDecimal(this.txbNDSSumm.Text), Util.Convert.ToDecimal(this.txbReestrPrice.Text),
                    Util.Convert.ToDateTime(ReestrDate), this.txbGTDNumber.Text, this.txbCertificateNumber.Text,
                    Util.Convert.ToDateTime(CertificateDate), sertId,
                    Util.Convert.ToDouble(this.txbMarkUp.Text), Util.Convert.ToDecimal(this.txbRetailPrice.Text),
                    this.txbNote.Text, DateTime.Now, FirstForm.Login);
                _par.lbNaklList_DoubleClick(_par.lbNaklList, EventArgs.Empty);
            }
            catch (Exception ee)
            {
                System.Diagnostics.Debug.WriteLine(ee.ToString());
            }
            this.Hide();
        }

        private void txbRetailPrice_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.DecimalValidation(txbRetailPrice, string.Empty);
        }

        private void txbMarkUp_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.DoubleValidation(txbMarkUp, string.Empty);
        }

        private void txbSupplierPrice_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(txbSupplierPrice.Text))
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !Util.Validator.DecimalValidation(txbSupplierPrice, string.Empty);
        }

        private void txbNDSSumm_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.DecimalValidation(txbNDSSumm, string.Empty);
        }

        private void AddRowWithInnerGoods_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        private void txbRetailPrice_KeyPress(object sender, KeyPressEventArgs e)
            {
            if (e.KeyChar == (char)Keys.Back)
                return;
            if (!(char.IsDigit(e.KeyChar) || e.KeyChar == ',' || e.KeyChar == '.'))
            {
            e.Handled = true;
            Console.Beep();
                }
            }

        private void txbCount_KeyDown(object sender, KeyEventArgs e)
            {
            
            }

        private void txbCount_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.Int32Validation(txbCount,string.Empty);
        }

        private void txbCount_KeyPress(object sender, KeyPressEventArgs e)
            {
            if (e.KeyChar == (char)Keys.Back)
                return;
            if (!char.IsDigit(e.KeyChar))
                {
                e.Handled = true;
                Console.Beep();
                }
            }
            #region рассчет цен
        /// <summary>
        /// Введена ли ставка НДС
        /// </summary>
        public bool IsNDS
        {
            get
            {
                string str = txbNDSTax.Text;
                if (string.IsNullOrEmpty(str))
                {
                    return false;
                }
                return true;
            }
        }
        /// <summary>
        /// Ставка НДС
        /// </summary>
        public byte NDS
        {
            get
            {
                string str = txbNDSTax.Text;
                if (string.IsNullOrEmpty(str))
                {
                    MessageBox.Show("Должно быть введено число или ничего");
                    txbNDSTax.Focus();
                    return 0;
                }
                byte d;
                if(!byte.TryParse(str, out d))
                {
                    return 0;
                }
                return d;
            }
            set
            {
                txbNDSTax.Text = value.ToString();
            }
        }
        /// <summary>
        /// введена цена поставщика с НДС
        /// </summary>
        public bool IsSupplierPriceWithNDS
        {
            get
            {
                string str = txbPriceSupplaerWithNDS.Text;
                if (string.IsNullOrEmpty(str))
                    return false;
                return true;
            }
        }
        /// <summary>
        /// Цена поставщика с НДС
        /// </summary>
        public decimal SupplierPriceWithNDS
        {
            get
            {
                string str = txbPriceSupplaerWithNDS.Text;
                if (string.IsNullOrEmpty(str))
                {
                    return 0;
                }
                str = str.Replace(',', '.');
                decimal d;
                if (!decimal.TryParse(str, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out d))
                {
                    MessageBox.Show("Должно быть введено вещественное число или ничего");
                    txbPriceSupplaerWithNDS.Focus();
                    return 0;
                }
                return d;
            }
            set
            {
                txbPriceSupplaerWithNDS.Text = value.ToString();
            }
        }
        /// <summary>
        /// Цена поставщика без НДС
        /// </summary>
        public bool IsSupplierPrice
        {
            get
            {
                string str = txbSupplierPrice.Text;
                if (string.IsNullOrEmpty(str))
                    return false;
                str = str.Replace(',', '.');
                decimal d;
                if (!decimal.TryParse(str, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out d))
                {
                    return false;
                }
                return true;
            }
        }
        /// <summary>
        /// Цена поставщика без налогов
        /// </summary>
        public decimal SupplierPrice
        {
            get
            {
                string str = txbSupplierPrice.Text;
                if (string.IsNullOrEmpty(str))
                    return 0;
                str = str.Replace(',', '.');
                decimal d;
                if (!decimal.TryParse(str, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out d))
                {
                    return 0;
                }
                return d;
            }
            set
            {
                txbSupplierPrice.Text = value.ToString();
            }
        }
        public bool IsCount
        {
            get
            {
                string str = txbCount.Text;
                if (string.IsNullOrEmpty(str))
                    return false;
                Int32 d;
                if (!Int32.TryParse(str, out d))
                {
                    return false;
                }
                return true;

            }
        }
        public Int32 Count
        {
            get
            {
                if (!IsCount)
                    return 0;
                string str = txbCount.Text;
                Int32 d;
                if (!Int32.TryParse(str, out d))
                {
                    txbCount.Text = string.Empty;
                    txbCount.Focus();
                    return 0;
                }
                return d;
            }
        }
        private bool _isChangeForm = false;
        /// <summary>
        /// свойство показывает менялась ли форма.
        /// </summary>
        public bool IsChangeForm
        {
            get { return _isChangeForm; }
            set { _isChangeForm = value; }
        }

        private void txbSupplierPrice_TextChanged(object sender, EventArgs e)
        {
            if (IsChangeForm)
                return;
            CalculateForm(txbSupplierPrice);
        }
        private void txbPriceSupplaerWithNDS_TextChanged(object sender, EventArgs e)
        {
            if (IsChangeForm)
                return;
            CalculateForm(txbPriceSupplaerWithNDS);
        }

        private void txbNDSTax_TextChanged(object sender, EventArgs e)
        {
            if (IsChangeForm)
                return;
            CalculateForm(txbNDSTax);
        }

        private void txbCount_TextChanged(object sender, EventArgs e)
        {
            if (IsChangeForm)
                return;
            string str = txbCount.Text;
            if (string.IsNullOrEmpty(str))
                return;
            CalculateForm(txbCount);
        }
        private void CalculateForm(TextBox tb)
        {
            IsChangeForm = true;
            #region пересчет формы
            if (!IsCount)
            {
                IsChangeForm = false;
                return;
            }
            if (!(IsSupplierPrice || IsSupplierPriceWithNDS))
            {
                IsChangeForm = false;
                return;
            }
            if (!IsNDS)
            {
                IsChangeForm = false;
                return;
            }
            //если поменяли цену без НДС
            if (tb == txbSupplierPrice)
            {
                decimal d = SupplierPrice + SupplierPrice * NDS / 100;
                SupplierPriceWithNDS = d;
                txbNDSSumm.Text = ((d - SupplierPrice) * Count).ToString();
                txbSummNoNDS.Text = (SupplierPrice * Count).ToString();
                IsChangeForm = false;
                return;
            }
            else
            {
                //если поменяли цену с НДС
                if (tb == txbPriceSupplaerWithNDS)
                {
                    decimal d = SupplierPriceWithNDS * ((decimal)NDS / (100 + (decimal)NDS));
                    d=decimal.Round(d,2,MidpointRounding.AwayFromZero);
                    d = SupplierPriceWithNDS - d;
                    txbSupplierPrice.Text = d.ToString();
                    txbNDSSumm.Text = ((SupplierPriceWithNDS - SupplierPrice) * Count).ToString();
                    txbSummNoNDS.Text = (SupplierPrice * Count).ToString();
                    IsChangeForm = false;
                    return;
                }
            }
            //Если считаем по цене с НДС
            if (rbWithNDS.Checked && IsSupplierPriceWithNDS)
            {
                decimal d = SupplierPriceWithNDS * ((decimal)NDS / (100 + (decimal)NDS));
                d = decimal.Round(d, 2, MidpointRounding.AwayFromZero);
                d = SupplierPriceWithNDS - d;
                txbSupplierPrice.Text = d.ToString();
                txbNDSSumm.Text = ((SupplierPriceWithNDS - SupplierPrice) * Count).ToString();
                txbSummNoNDS.Text = (SupplierPrice * Count).ToString();
                IsChangeForm = false;
                return;
            }
            //Если считаем по цене без НДС
            if (rbNoNDS.Checked && IsSupplierPrice)
            {
                decimal d = SupplierPrice + SupplierPrice * NDS / 100;
                SupplierPriceWithNDS = d;
                txbNDSSumm.Text = ((d - SupplierPrice) * Count).ToString();
                txbSummNoNDS.Text = (SupplierPrice * Count).ToString();
                IsChangeForm = false;
                return;
            }
            #endregion
            IsChangeForm = false;
        }
            #endregion

        private void cbGoods_Leave(object sender, EventArgs e)
        {
          //  cbGoods.DroppedDown = true;
        }
        GoodsList _goodsList = null;
        private void button4_Click(object sender, EventArgs e)
        {
            if (_goodsList == null)
            {
                _goodsList = new GoodsList();
            }
            System.Windows.Forms.DialogResult dr = _goodsList.ShowDialog(this);
            
        }

        private void selecter1_MySelectButtonClick(object sender, EventArgs e)
        {
            Dictionary.NewGoods ng = new DIProject.Dictionary.NewGoods();
            DialogResult dr = ng.ShowDialog();
            if (dr == DialogResult.OK)
            {
                selecter1.SelectedText = ng.SelectedName;
                selecter1.SelectedValue = ng.SelectedId;
            }
            ng.Close();
        }

       

       

    }
}